package com.itheima.reggie.common;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handeleException(SQLIntegrityConstraintViolationException exception){
     //判定当前异常信息中是否包含 Duplicate entry
     if (exception.getMessage().contains("Duplicate entry")){
         String errorMsg = exception.getMessage().split(" ")[2];
         return R.error(errorMsg+"已存在");
     }
     return R.error("操作失败");
   }

   @ExceptionHandler(Exception.class)
    public R Exceptions(Exception exception){
       return R.error("对不起，操作失败");
   }

   @ExceptionHandler(CustomException.class)
    public R hanleException(CustomException customException){
        return R.error(customException.getMessage());
   }
}
